import {
  addPatient,
  deletePatient,
  patientList,
  updatePatient,
} from '@/services/PatientService';
import { Patient } from '@/types';
import { useModel } from '@@/exports';
import {
  ModalForm,
  ProFormDateTimePicker,
  ProFormDigit,
  ProFormRadio,
  ProFormText,
} from '@ant-design/pro-form';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-table';
import { useAccess, useLocation } from '@umijs/max';
import { Button, Popconfirm, message } from 'antd';
import { useRef, useState } from 'react';
import styles from './index.less';

const PatientList = ({ clickText }: { clickText: string }) => {
  const [_message, contextHolder] = message.useMessage();
  const { peerServer } = useModel('global');
  const access = useAccess();
  const location = useLocation();
  const { patient, setPatient } = useModel('patient');
  const columns: ProColumns<Patient>[] = [
    {
      title: '姓名',
      dataIndex: 'name',
      editable: false,
      width: '200px',
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: '100px',
      search: false,
      valueEnum: {
        0: '男',
        1: '女',
      },
    },
    {
      title: '年龄',
      dataIndex: 'age',
      width: '100px',
      search: false,
    },
    {
      title: '住院号',
      dataIndex: 'hospitalNumber',
      width: '200px',
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '手术时间',
      dataIndex: 'operationTime',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true,
      search: {
        transform: (value) => {
          return value[0] + ',' + value[1];
        },
      },
    },
    {
      dataIndex: 'search',
      editable: false,
      width: '200px',
      hideInForm: true,
      hideInTable: true,
      fieldProps: {
        placeholder: '搜索患者姓名/住院号',
      },
    },
    {
      title: '手术时间',
      dataIndex: 'operationTime',
      valueType: 'dateTime',
      width: '300px',
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '科室',
      dataIndex: 'department',
      width: '200px',
      search: false,
    },
    {
      title: '医生',
      dataIndex: 'doctor',
      width: '200px',
      search: false,
    },
    {
      title: '手术车号',
      dataIndex: 'operateCarNum',
      width: '200px',
      search: false,
    },
    {
      title: '手术间',
      dataIndex: 'operationRoomNo',
      width: '200px',
      search: false,
    },
    {
      title: '设备名',
      dataIndex: 'equipmentName',
      width: '200px',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: '180px',
      render: (text, record, _, action) => [
        <ModalForm<Patient>
          initialValues={record}
          key="editable"
          width={500}
          title="修改患者"
          trigger={<Button>编辑</Button>}
          // form={form}
          autoFocusFirstInput
          modalProps={{
            centered: true,
            destroyOnClose: true,
            maskClosable: false,
            className: styles.modalFormStyle,
          }}
          onFinish={async (values) => {
            console.log('values', values);
            const { data } = await updatePatient(peerServer, values);
            if (data.success) {
              ref.current?.reload(true);
              _message.success('修改成功');
              return true;
            } else {
              _message.error('修改失败');
              return false;
            }
          }}
        >
          <ProFormText name="id" hidden />
          <ProFormText
            name="name"
            label="姓名"
            placeholder="请输入姓名"
            rules={[{ required: true }]}
          />
          <ProFormRadio.Group
            name="sex"
            label="性别"
            placeholder="请选择性别"
            options={[
              { label: '男', value: 0 },
              { label: '女', value: 1 },
            ]}
          />
          <ProFormDigit
            name="age"
            label="年龄"
            placeholder="请输入年龄"
            fieldProps={{ precision: 0 }}
          />
          <ProFormText
            name="hospitalNumber"
            label="住院号"
            placeholder="请输入住院号"
            rules={[{ required: true }]}
          />
          <ProFormDateTimePicker
            fieldProps={{ format: 'YYYY-MM-DD HH:mm' }}
            name="operationTime"
            label="手术时间"
            rules={[{ required: true }]}
            placeholder="请选择手术时间"
          />
          <ProFormText
            name="department"
            label="科室"
            placeholder="请输入科室"
          />
          <ProFormText name="doctor" label="医生" placeholder="请输入医生" />

          <ProFormText
            name="operateCarNum"
            label="手术车号"
            placeholder="请输入手术车号"
          />
          <ProFormText
            name="operationRoomNo"
            label="手术间"
            placeholder="请输入手术间"
          />
          <ProFormText
            name="equipmentName"
            label="设备名"
            placeholder="请输入设备名"
          />
        </ModalForm>,
        <Popconfirm
          title="确认删除吗？"
          onConfirm={async () => {
            const { data } = await deletePatient(peerServer, record.id);
            if (data.success) {
              ref.current?.reload(true);
              _message.success('删除成功');
            } else {
              _message.error('删除失败');
            }
          }}
        >
          <Button key="delete">删除</Button>
        </Popconfirm>,
        <Button
          key="select"
          onClick={async () => {
            // setPatient(record);
            // setIsModalOpen(false);
            await window.tm?.ipcRenderer.invoke('updatePatientActive', record);
            await window.tm?.ipcRenderer.invoke('closeObsModal');
          }}
        >
          选择
        </Button>,
      ],
    },
  ];
  const [isModalOpen, setIsModalOpen] = useState(false);
  const ref = useRef<ActionType>();
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // useEffect(() => {
  //   if (access.allowVideoMatrix) {
  //     if (patient == undefined && location.pathname !== '/settings') {
  //       setIsModalOpen(true);
  //     }
  //   }
  // }, []);

  return (
    <div style={{ userSelect: 'none', height: '100%' }}>
      {contextHolder}
      {/*<div onClick={showModal}>{clickText}</div>*/}
      {/*<Modal*/}
      {/*  closable={patient != undefined}*/}
      {/*  footer={false}*/}
      {/*  destroyOnClose={true}*/}
      {/*  centered*/}
      {/*  width="90%"*/}
      {/*  bodyStyle={{*/}
      {/*    height: '660px',*/}
      {/*  }}*/}
      {/*  title="请选择一位患者"*/}
      {/*  open={isModalOpen}*/}
      {/*  onOk={handleOk}*/}
      {/*  onCancel={handleCancel}*/}
      {/*  maskClosable={false}*/}
      {/*>*/}
      <ProTable<Patient>
        style={{ userSelect: 'none', height: '100%' }}
        actionRef={ref}
        size="small"
        rowKey="id"
        className={styles.proTableStyle}
        headerTitle="患者列表"
        columns={columns}
        options={{
          setting: false,
          density: false,
          reload: true,
        }}
        toolBarRender={() => [
          <ModalForm<Patient>
            width={500}
            title="新建患者"
            trigger={
              <Button key="addPatient" type="primary">
                新建患者
              </Button>
            }
            // form={form}
            autoFocusFirstInput
            modalProps={{
              centered: true,
              destroyOnClose: true,
              maskClosable: false,
              className: styles.modalFormStyle,
            }}
            onFinish={async (values) => {
              // console.log(values);
              const { data } = await addPatient(peerServer, values);
              if (data.success) {
                ref.current?.reload(true);
                _message.success('提交成功');
                return true;
              } else {
                _message.error('提交失败，住院号重复');
                return false;
              }
            }}
          >
            <ProFormText
              name="name"
              label="姓名"
              placeholder="请输入姓名"
              rules={[{ required: true }]}
            />
            <ProFormRadio.Group
              name="sex"
              label="性别"
              placeholder="请选择性别"
              options={[
                { label: '男', value: 0 },
                { label: '女', value: 1 },
              ]}
            />
            <ProFormDigit
              name="age"
              label="年龄"
              placeholder="请输入年龄"
              fieldProps={{ precision: 0 }}
            />
            <ProFormText
              name="hospitalNumber"
              label="住院号"
              placeholder="请输入住院号"
              rules={[{ required: true }]}
            />
            <ProFormDateTimePicker
              width={'100%'}
              fieldProps={{ format: 'YYYY-MM-DD HH:mm' }}
              name="operationTime"
              label="手术时间"
              rules={[{ required: true }]}
              placeholder="请选择手术时间"
            />
            <ProFormText
              name="department"
              label="科室"
              placeholder="请输入科室"
            />
            <ProFormText name="doctor" label="医生" placeholder="请输入医生" />
            <ProFormText
              name="operateCarNum"
              label="手术车号"
              placeholder="请输入手术车号"
            />
            <ProFormText
              name="operationRoomNo"
              label="手术间"
              placeholder="请输入手术间"
            />
            <ProFormText
              name="equipmentName"
              label="设备名"
              placeholder="请输入设备名"
            />
          </ModalForm>,
        ]}
        request={async (params) => {
          // console.log(params);
          try {
            const { data } = await patientList(peerServer, {
              current: params.current as number,
              size: params.pageSize as number,
              operationTime: params.operationTime,
              search: params.search,
            });
            return {
              success: data.success,
              data: data.data.records,
              total: data.data.total,
            };
          } catch {
            _message.error('连接服务器失败');
            return {
              success: false,
            };
          }
        }}
        pagination={{ pageSize: 10 }}
      />
      {/*</Modal>*/}
    </div>
  );
};

// export default PatientList;

export default PatientList;
